package lhc.learn.bio;

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * Created by Lihc on 2016/3/24.
 */
public class TimeServerHandler implements Runnable {

    /**
     * socket
     */
    private Socket socket;

    /**
     * 构造方法
     *
     * @param socket
     */
    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    /**
     * 进程执行方法
     */
    @Override
    public void run() {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            String currentTime = null;
            String body = null;
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);
            while (true) {
                body = reader.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("receive message:" + body);
                currentTime = "time".equals(body) ? new Date().toString() : "nothing";
                writer.println(currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
            IOUtils.closeQuietly(socket);
        }
    }
}
